package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.LoginConstant;
import com.hmdp.utils.RegexUtils;
import net.sf.jsqlparser.statement.select.KSQLWindow;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(LoginFormDTO loginForm, HttpSession session) {
        // 1. 校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone))
            // 校验失败, 返回异常
            return Result.fail(LoginConstant.PHONE_INVALID);
        // 2. 校验成功, 生成验证码
        String code = RandomUtil.randomNumbers(6);
        // 3. 将验证码保存到redis中
        stringRedisTemplate.opsForValue().set(LoginConstant.REDIS_CODE + phone,code);
        // 4. 模拟发送验证码成功
        log.debug("发送验证码成功");

        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {
        // 1. 校验手机号
        String phone = loginForm.getPhone();
        if (RegexUtils.isPhoneInvalid(phone))
            // 校验失败, 返回异常
            return Result.fail(LoginConstant.PHONE_INVALID);
        // 2. 校验验证码
        String code = stringRedisTemplate.opsForValue().get(LoginConstant.REDIS_CODE + loginForm.getPhone());
        if (loginForm.getCode() == null || code.equals(loginForm.getCode())){
            return Result.fail(LoginConstant.CODE_ERROR);
        }
        // 3. 从数据库中查询用户
        User user = this.query().eq("phone", loginForm.getPhone()).one();
        // 4. 判断用户是否注册
        if (user == null){
            // 注册用户
            user = createUserWithPhone(phone);
        }
        // 5. 生成随机token
        String token = UUID.randomUUID().toString(true);
        // 6. 将用户保存到redis中
        Map<String, Object> map = BeanUtil.beanToMap(
                user,
                new HashMap<>(),
                CopyOptions
                .create()
                        .setIgnoreNullValue(true));
        String tokenKey = LoginConstant.REDIS_USER + token;
        stringRedisTemplate.opsForHash().putAll(tokenKey,map);
        return null;
    }
    private User createUserWithPhone(String phone){
        User user = new User();
        user.setPhone(phone);
        user.setNickName(LoginConstant.USER_NICK_NAME);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        return user;
    }
}
